#!/bin/sh

DEBUG=0
DEBUGFILE=/conf/.cron/runparts.log

#exit 0

[ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: -= START =-" >> $DEBUGFILE

if [ -f /conf/.cron/isrun.lock ]; then
    [ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: Found /conf/.cron/isrun.lock" >> $DEBUGFILE
#check for stale lock file
    D1=`date +%s -r /conf/.cron/isrun.lock`
    D2=`date +%s`
    D3=$((D2-D1))
    if [ $D3 -ge 1800 ] || [ $D3 -lt 0 ]; then
        [ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: Lock file is stale. Remove it" >> $DEBUGFILE
        rm -f /conf/.cron/isrun.lock
    else
        exit 0
    fi
fi

#Check for mounted HDD
if [ `mount | grep '/mnt/data' | wc -l` -le 0 ]; then
    [ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: HDD not mounted" >> $DEBUGFILE
    exit 0
fi

#Create lock file No.1
[ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: Create lock file No.1" >> $DEBUGFILE

#Start transmission-daemon and create LOCK file No.2 if all ok

if [ `netstat -lean | grep 9091 | wc -l` -le 0 ]; then
    [ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: Transmission not running" >> $DEBUGFILE
    export TRANSMISSION_WEB_HOME=/conf/transmission/web
    nice -n 10 /conf/.cron/transmission-daemon -g /conf/.config
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
        [ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: Failed to run transmission. Remove lock file No.1" >> $DEBUGFILE
        rm -f /conf/.cron/isrun.lock
        exit 1
    else
        [ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: OK. Transmission running. Create lock file No.2" >> $DEBUGFILE
        touch /conf/.cron/firstrun.lock
    fi
fi

if [ `netstat -lean | grep 9091 | wc -l` -ge 1 ]; then
    [ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: Transmission still running. OK" >> $DEBUGFILE
    if [ ! -f /conf/.cron/firstrun.lock ]; then
        [ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: It's not first run. Start queue.sh in background" >> $DEBUGFILE
        nice -n 10 /conf/.cron/queue.sh &
    fi
fi

[ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: Remove lock files." >> $DEBUGFILE

rm -f /conf/.cron/isrun.lock
rm -f /conf/.cron/firstrun.lock

[ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: Start get.sh in background" >> $DEBUGFILE

nice -n 10 /conf/.cron/get.sh &

[ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: Start cleanlog.sh in background" >> $DEBUGFILE
/conf/.cron/cleanlog.sh &

[ $DEBUG -eq 0 ] || echo "[`date +\"%F %T\"`]: -= STOP =-" >> $DEBUGFILE
